package com.bdbit.ChargingStation.services;

import com.bdbit.ChargingStation.entity.ChargingOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;

@Service

public class ChargingTimerService {
    private static final Logger log = LoggerFactory.getLogger(ChargingTimerService.class);
    
    @Autowired
    private ChargingOrderService chargingOrderService;
    
    @Autowired
    private MqttServerService mqttServerService;

    //@Scheduled(fixedRate = 30000)
    //@ConditionalOnProperty(name = "task.checkChargingCompletion", havingValue = "true")
    public void checkChargingCompletion() {
        // 获取所有进行中的订单
        List<ChargingOrder> activeOrders = chargingOrderService.getActiveOrders();
        if(activeOrders.size() == 0){
            return;
        }
        for (ChargingOrder order : activeOrders) {
            // 确保订单状态为充电中
            if (order.getStatus() != ChargingOrder.STATUS_CHARGING) {
                continue;
            }
            
            // 计算剩余充电时间
            long remainingTime = calculateRemainingTime(order);
            
            if (remainingTime <= 0) {
                completeCharging(order);
            }
        }
    }
    
    private long calculateRemainingTime(ChargingOrder order) {
        // 添加空值检查
        if (order == null || order.getStartTime() == null || order.getChargingMinutes() == null) {
            log.warn("订单信息不完整，无法计算剩余时间: order={}", order);
            return 0;
        }
        
        // 计算已充电时间（毫秒）
        long elapsed = System.currentTimeMillis() - order.getStartTime().getTime();
        
        // 计算总充电时间（分钟转毫秒）
        long totalChargingTime = order.getChargingMinutes() * 60 * 1000;
        
        return totalChargingTime - elapsed;
    }
    
    private void completeCharging(ChargingOrder order) {
        try {
            // 检查订单是否已经完成
            if (order.getStatus() == ChargingOrder.STATUS_COMPLETED) {
                log.debug("订单已完成，跳过处理: orderId={}", order.getOrderId());
                return;
            }
            
            // 2. 更新订单状态为已完成
            order.setStatus(ChargingOrder.STATUS_COMPLETED);
            chargingOrderService.updateOrder(order);
            
            log.info("充电完成处理成功: orderId={}", order.getOrderId());
        } catch (Exception e) {
            log.error("充电完成处理失败: orderId={}", order.getOrderId(), e);
        }
    }
}